package com.geekbang.cn;

import org.eclipse.microprofile.config.spi.ConfigSource;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class HttpServletParameterConfigSource implements ConfigSource, ServletRequestListener {

    private ThreadLocal<Map<String,String>> httpServletRequestThreadLocal = new ThreadLocal<>();

    @Override
    public Set<String> getPropertyNames() {
        return httpServletRequestThreadLocal.get().keySet();
    }

    @Override
    public int getOrdinal() {
        return 500;
    }

    @Override
    public String getValue(String propertyName) {
        return httpServletRequestThreadLocal.get().get(propertyName);
    }

    @Override
    public String getName() {
        return "HttpServletParameterConfigSource";
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {

    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        Map<String,String> map = new HashMap<>();
        ServletRequest servletRequest = sre.getServletRequest();
        Enumeration<String> enumeration = servletRequest.getParameterNames();
        while(enumeration.hasMoreElements())
        {
            String parameterName = enumeration.nextElement();
            map.put(parameterName,servletRequest.getParameter(parameterName));
        }
    }
}
